#include "DeviceManager.h"

#include <QDebug>

#include "ConfigManager.h"
#include "ConstData.h"
#include "DeviceHelper.h"
#include "DeviceSampleHelper.h"
#include "DeviceSpikeHelper.h"
#include "DeviceWcsHelper.h"
#include "DeviceYclHelper.h"
#include "ModbusManager.h"
#include "define.h"
DeviceManager* DeviceManager::instance()
{
    static DeviceManager instance;
    return &instance;
}

DeviceManager::DeviceManager(/* args */)
{
    ModbusManager* modbusManager = ModbusManager::instance();
    QStringList deviceLis = modbusManager->getDeviceList();
    for (auto device : deviceLis) {
        switch (DEVICE_MAP[device].deviceType) {
            case DeviceType_normal:
                m_deviceHelpers.insert(device, new DeviceHelper(device));
                break;
            case DeviceType_wcs:
                m_deviceHelpers.insert(device, new DeviceWcsHelper(device));
                break;
            case DeviceType_ycl:
                m_deviceHelpers.insert(device, new DeviceYclHelper(device));
                break;
            case DeviceType_spike:
                m_deviceHelpers.insert(device, new DeviceSpikeHelper(device));
                break;
            case DeviceType_sample:
                m_deviceHelpers.insert(device, new DeviceSampleHelper(device));
                break;
            default:
                break;
        }
    }
    for (auto helper : m_deviceHelpers) {
        connect(helper, &IDevice::errorOccurred, this, [this, helper](const QString& errorMessage) {
            emit errorOccurred(helper->getDeviceName(), errorMessage);
        });
        connect(helper, &IDevice::commStatusChanged, this, [this, helper](const bool& commStatus) {
            emit commStatusChanged(helper->getDeviceName(), commStatus);
        });
        connect(helper, &IDevice::measurementOutOfRange, this,
                [this](const QString& deviceName, float value, float lowerLimit, float upperLimit) {
                    emit measurementOutOfRange(deviceName, value, lowerLimit, upperLimit);
                });
    }
    startAllDataMonitoring();
}

DeviceManager::~DeviceManager()
{
    // saveConfiguration();
    qDeleteAll(m_deviceHelpers);  // 释放所有设备助手对象
}

IDevice* DeviceManager::getDeviceHelper(const QString& deviceName)
{
    if (m_deviceHelpers.contains(deviceName)) {
        return m_deviceHelpers[deviceName];
    }
    return nullptr;
}

void DeviceManager::startAllDataMonitoring()
{
    for (auto helper : m_deviceHelpers) {
        helper->startDataMonitoring();
    }
}

void DeviceManager::stopAllDataMonitoring()
{
    for (auto helper : m_deviceHelpers) {
        helper->stopDataMonitoring();
    }
}

void DeviceManager::stopAllDevices()
{
    for (auto helper : m_deviceHelpers) {
        helper->stop();
    }
}
